package com.edu.base.rest;

import com.edu.base.common.ParamsUtil;
import com.edu.base.ums.grade.domain.ClsMemberGrade;
import com.edu.base.ums.grade.service.IClsMemberGradeService;
import com.edu.base.ums.member.domain.ClsMember;
import com.edu.base.ums.member.domain.ClsMemberVo;
import com.edu.base.ums.member.mapper.ClsMemberMapper;
import com.edu.base.ums.member.service.IClsMemberService;
import com.google.common.collect.Lists;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.obs.ObsService;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.bean.BeanUtils;
import com.ruoyi.framework.config.ServerConfig;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.List;


@Api(tags = "4、会员相关接口")
@RestController
@RequestMapping("/api/member")
public class AppMemberController extends BaseController {
  @Autowired
  private IClsMemberService clsMemberService;

  @Autowired
  private IClsMemberGradeService clsMemberGradeService;

  @Autowired
  private HttpServletRequest request;

  @Autowired
  private ClsMemberMapper clsMemberMapper;
  @Autowired
  private IClsMemberGradeService memberGradeService;

  @Autowired
  private ServerConfig serverConfig;

  @Autowired
  private ObsService obsService;

  /**
   * 获取会员信息
   */
  @GetMapping(value = "/getInfo")
  @ApiOperation(value = "获取会员信息", response = ClsMember.class)
  @ApiImplicitParams({
      @ApiImplicitParam(name = "id", value = "会员id"),
      @ApiImplicitParam(name = "phone", value = "手机号码"),
      // 	   @ApiImplicitParam(name = "weixinOpenid", value = "微信Openid"),
      // 	   @ApiImplicitParam(name = "qqToken", value = "QQOpenid"),
  })
  public AjaxResult getInfo(String id, String phone) {
    List<ClsMember> list = Lists.newArrayList();
    if (StringUtils.isNotBlank(id)) {
      ClsMember clsMember = clsMemberService.selectClsMemberById(id);
      if (clsMember != null) {
        list.add(clsMember);
      }

    }
    if (StringUtils.isNotBlank(phone)) {
      list = clsMemberService.selectClsMemberByPhone(phone);
    }
    //if(StringUtils.isNotBlank(weixinOpenid)) list = clsMemberMapper.getMemberInfoByWeixinOpenid(weixinOpenid);
    //if(StringUtils.isNotBlank(qqtoken)) list = clsMemberMapper.getMemberInfoByQqOpenid(qqtoken);
    //if(StringUtils.isNotBlank(blogToken)) list = clsMemberMapper.findWeiboByIdentifier(blogToken);
    if (CollectionUtils.isEmpty(list)) {
      return AjaxResult.error("没有该会员信息");
    }
    ClsMember entity = list.get(0);
    return AjaxResult.success(entity);
  }

  @PostMapping(value = "/upLoadUserHeadImg")
  @ApiOperation(value = "上传会员头像")
  public AjaxResult updateUserHeadImg(MultipartFile file) {
    try {
//      // 上传文件路径
//      String filePath = RuoYiConfig.getUploadPath();
//      // 上传并返回新文件名称
//      String fileName = FileUploadUtils.upload(filePath, file);
//      String url = serverConfig.getUrl() + fileName;
//      AjaxResult ajax = AjaxResult.success();
//      ajax.put("fileName", fileName);
//      ajax.put("url", url);
//      return ajax;

      String url = obsService.uploadFile(file, "default");
      AjaxResult ajax = AjaxResult.success();
      ajax.put("fileName", file.getOriginalFilename());
      ajax.put("url", url);
      return ajax;
    } catch (Exception e) {
      return AjaxResult.error(e.getMessage());
    }
  }

  @PostMapping(value = "/updateMember")
  @ApiOperation(value = "更新会员信息")
  //	@ApiImplicitParams({
  //			@ApiImplicitParam(name = "id", value = "会员id",required = true),
  //			@ApiImplicitParam(name = "phone", value = "手机号码"),
  //	})
  public AjaxResult updateUserStatus(@RequestBody ClsMemberVo clsMemberVo) {
    ClsMember clsMember = clsMemberService.selectClsMemberById(clsMemberVo.getId());
    if (clsMember == null) {
      return AjaxResult.error("无此用户");
    } else {
      ClsMember member = new ClsMember();
      BeanUtils.copyBeanProp(member, clsMemberVo);
      return toAjax(clsMemberService.updateClsMember(member));
    }

  }

  @GetMapping("/grade")
  @ApiOperation(value = "获取办理会员等级列表")
  public AjaxResult getMemberGrade() {
    ClsMemberGrade memberGrade = new ClsMemberGrade();
    List<ClsMemberGrade> clsMemberGrades = memberGradeService.selectClsMemberGradeList(memberGrade);
    return AjaxResult.success(clsMemberGrades);
  }


  @GetMapping("/teacherPrice")
  @ApiOperation(value = "获取老师批改作文价格")
  public AjaxResult getTeacherPrice() {
    ClsMemberGrade memberGrade = new ClsMemberGrade();
    memberGrade.setType("2");
    List<ClsMemberGrade> clsMemberGrades = memberGradeService.selectClsMemberGradeList(memberGrade);
    return AjaxResult.success(clsMemberGrades);
  }


  /**
   * 修改会员
   */
  @PostMapping(value = "/editInfo")
  @ApiOperation("修改会员信息")
  @ApiImplicitParams({

      @ApiImplicitParam(name = "phone", value = "手机号码"),
      @ApiImplicitParam(name = "userName", value = "用户名"),
      @ApiImplicitParam(name = "weixinOpenid", value = "微信Openid"),
      @ApiImplicitParam(name = "qqToken", value = "QQtoken"),
      @ApiImplicitParam(name = "blogToken", value = "微博token")
  })
  @ApiIgnore
  public AjaxResult editInfo(String phone, String userName, String weixinOpenid, String qqToken, String blogToken) {
    ClsMember clsMember = new ClsMember();
    clsMember.setPhone(phone);
    clsMember.setUserName(userName);
    clsMember.setWeixinOpenid(weixinOpenid);
    clsMember.setQqToken(qqToken);
    clsMember.setBlogToken(blogToken);

    ClsMember vo = null;
    // TODO 传过来的值做匹配
    if (StringUtils.isNotBlank(clsMember.getPhone())) {
      List<ClsMember> phoneList = clsMemberService.selectClsMemberByPhone(clsMember.getPhone());
      if (CollectionUtils.isNotEmpty(phoneList)) {
        vo = phoneList.get(0);
      }
    } else if (StringUtils.isNotBlank(clsMember.getUserName())) {
      List<ClsMember> userNameList = clsMemberService.selectClsMemberByUserName(clsMember.getUserName());
      if (CollectionUtils.isNotEmpty(userNameList)) {
        vo = userNameList.get(0);
      }
    } else if (StringUtils.isNotBlank(clsMember.getWeixinOpenid())) {
      List<ClsMember> wxOpenid = clsMemberMapper.getMemberInfoByWeixinOpenid(clsMember.getWeixinOpenid());
      if (CollectionUtils.isNotEmpty(wxOpenid)) {
        vo = wxOpenid.get(0);
      }
    } else if (StringUtils.isNotBlank(clsMember.getQqToken())) {
      List<ClsMember> qqOpenid = clsMemberMapper.getMemberInfoByQqOpenid(clsMember.getQqToken());
      if (CollectionUtils.isNotEmpty(qqOpenid)) {
        vo = qqOpenid.get(0);
      }
    } else if (StringUtils.isNotBlank(clsMember.getBlogToken())) {
      List<ClsMember> blogTokens = clsMemberMapper.findWeiboByIdentifier(clsMember.getQqToken());
      if (CollectionUtils.isNotEmpty(blogTokens)) {
        vo = blogTokens.get(0);
      }
    }
    if (vo == null) {
      return AjaxResult.error("没有匹配上该用户信息");
    }
    BeanUtils.copyBeanProp(clsMember, vo);

    return toAjax(clsMemberService.updateClsMember(clsMember));
  }


  /**
   * 办理会员
   *
   * @param
   * @return
   */
  @GetMapping(value = "/applyMemberShipList")
  @ApiOperation("办理会员等级列表")
  @ApiIgnore
  public TableDataInfo applyMemberShipList() {
    startPage();
    List<ClsMemberGrade> list = clsMemberGradeService.selectClsMemberGradeList(new ClsMemberGrade());
    list.forEach(v -> {
      // TODO  当 月数*原价格 = 优惠价格 显示 8/月  ，不相等  显示原价￥48
      //long  amount =  new BigDecimal(v.getMemberMonth()).multiply(v.getOriginalPrice()).longValue();
      if (v.getDiscountPrice() != null) {
        // TODO  当优惠价等于原价
        if (v.getDiscountPrice().compareTo(v.getOriginalPrice()) == 0) {
          long defaultAmount = v.getOriginalPrice().divide(new BigDecimal(v.getMemberMonth()), 0, BigDecimal.ROUND_HALF_UP).longValue();
          v.setPriceContent("￥" + defaultAmount + "/月");
        } else {
          v.setPriceContent("原价￥" + v.getOriginalPrice());
        }

      } else {
        // 显示   原价/月数  --
        long defaultAmount = v.getOriginalPrice().divide(new BigDecimal(v.getMemberMonth()), 0, BigDecimal.ROUND_HALF_UP).longValue();
        v.setPriceContent("￥" + defaultAmount + "/月");
        v.setDiscountPrice(v.getOriginalPrice());
      }

    });
    return getDataTable(list);
  }


  /**
   * 办理会员
   *
   * @param
   * @return
   */
  @PostMapping(value = "/addMemberShip")
  @ApiOperation("办理会员等级")
  @ApiImplicitParams({
      @ApiImplicitParam(name = "memberGradeId", value = "会员等级ID"),
      @ApiImplicitParam(name = "appUserId", value = "当期用户ID"),

  })
  @ApiIgnore
  public AjaxResult addMemberShip(String memberGradeId, String appUserId) {
    List<String> list = ParamsUtil.listAllParams(request);
    if (!list.isEmpty()) {
      list.remove("memberGradeId");
      if (list.size() > 10) {
        list = list.subList(0, 10);
      }
    }

    ClsMember clsMember = clsMemberService.selectClsMemberById(appUserId);
    if (clsMember != null)
      return AjaxResult.error("用户还未登录,请先登录");

    ClsMemberGrade clsMemberGrade = clsMemberGradeService.selectClsMemberGradeById(memberGradeId);
    clsMemberService.applyMemberShip(clsMember, clsMemberGrade.getMemberMonth());

    String msg = "";
    String param = String.join("、", list);
    if (StringUtils.isNotBlank(param)) {
      msg += "参数列中的" + param + "等参数并未定义在参数列表中，为无效参数。";
    }
    if (StringUtils.isNotBlank(msg)) {
      return AjaxResult.error(msg);
    }

    return AjaxResult.success();
  }

}
